import type { IDateTimeHeaderOptions } from '@/app/[locale]/admin/home/date-time-header';
import DateTimeHeader from '@/app/[locale]/admin/home/date-time-header';
import { useEffect, useRef, useState } from 'react';
import Chart from '@/lib/chart';
import useToast from '@/hooks/useToast';
import { useQuery } from '@tanstack/react-query';
import { queryNginxLogsWebsiteQuarterlyAccessCounts } from '@/services/api';
import type { INginxLogsWebsiteQuarterlyAccessCounts } from '@/interfaces';
import type { ChartData, ChartOptions } from 'chart.js';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function WebsiteQuarterlyAccessCounts({
  translatedFields,
}: {
  translatedFields: PrefixedTTranslatedFields<'homeAdminPage'>;
}) {
  const canvas = useRef<HTMLCanvasElement>(null);
  const chartRef = useRef<Chart<'bar', any, any>>();
  const [params, setParams] = useState({
    quarters: [1, 2, 3, 4],
  });
  const [options, setOptions] = useState<Partial<IDateTimeHeaderOptions>>({
    refreshOptions: {
      isLoading: false,
    },
    configs: {
      hideLeftContent: true,
    },
  });
  const { show } = useToast();

  const queryNginxLogsWebsiteQuarterlyAccessCountsQuery = useQuery(
    ['/nginx', '/logs', '/website', '/quarterly-access-counts', params],
    async (context) => {
      return (await queryNginxLogsWebsiteQuarterlyAccessCounts({
        query: context.queryKey[4] as any,
      })) as INginxLogsWebsiteQuarterlyAccessCounts;
    },
  );

  useEffect(() => {
    const current = canvas.current;
    const content = queryNginxLogsWebsiteQuarterlyAccessCountsQuery.data;
    if (current && content) {
      const labels = content.dates.map((item) => 'Q' + item);
      const values = Object.values(content.ranges);
      const data = {
        labels,
        datasets: [
          {
            label: translatedFields.visits,
            borderRadius: Number.MAX_VALUE,
            data: values,
          },
        ],
      } as ChartData<'bar'>;
      const options = {
        responsive: true,
      } as ChartOptions<'bar'>;

      chartRef.current = new Chart(current, {
        type: 'bar',
        data,
        options,
      });
    }

    return () => {
      if (current) {
        chartRef.current?.destroy();
      }
    };
  }, [queryNginxLogsWebsiteQuarterlyAccessCountsQuery.data]);

  async function onClickRefresh() {
    try {
      setOptions({
        ...options,
        refreshOptions: {
          isLoading: true,
        },
      });

      await queryNginxLogsWebsiteQuarterlyAccessCountsQuery.refetch();
      show({
        type: 'SUCCESS',
        message: translatedFields.refreshCompleted,
      });
    } catch (e) {
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setOptions({
        ...options,
        refreshOptions: {
          isLoading: false,
        },
      });
    }
  }

  return (
    <div className="card">
      <div className="card-header bg-transparent">
        <DateTimeHeader
          options={{
            clickOptions: {
              onClickRefresh,
            },
            refreshOptions: options.refreshOptions!,
            configs: options.configs!,
          }}
          translatedFields={translatedFields}
        />
      </div>
      <div className="card-body">
        {queryNginxLogsWebsiteQuarterlyAccessCountsQuery.data && (
          <div>
            <canvas ref={canvas}></canvas>
          </div>
        )}

        {queryNginxLogsWebsiteQuarterlyAccessCountsQuery.isError && (
          <Alert
            message={queryNginxLogsWebsiteQuarterlyAccessCountsQuery.error}
            type="error"
          />
        )}

        {queryNginxLogsWebsiteQuarterlyAccessCountsQuery.isLoading && (
          <AlertLoad />
        )}
      </div>
    </div>
  );
}
